package app.modules.security.persistence.dao;

import app.modules.security.dto.web.role.WebRoleDTO;
import app.modules.security.dto.web.role.WebRoleQueryDTO;
import app.modules.security.persistence.mapper.RoleMapper;
import app.modules.security.util.conversion.RoleConvertUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.CollectionUtil;
import jasmine.framework.common.util.StringUtil;
import jasmine.framework.database.mybatisplus.dao.BaseI18nEntityDAO;
import jasmine.framework.database.mybatisplus.wrapper.LambdaQueryWrapperWithI18n;
import jasmine.security.rbac.model.SecRole;
import org.springframework.stereotype.Repository;

import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;

/**
 * @author mh.z
 */
@Repository
public class RoleDAO extends BaseI18nEntityDAO<RoleMapper, SecRole> {

    /**
     * 分页查询角色
     *
     * @param queryDTO
     * @param page
     * @return
     */
    public List<WebRoleDTO> pageWebRoleDTOsByCond(WebRoleQueryDTO queryDTO, Page page) {
        CheckUtil.notNull(queryDTO, "queryDTO null");
        CheckUtil.notNull(page, "page null");
        LambdaQueryWrapperWithI18n<SecRole> wrapper = LambdaQueryWrapperWithI18n.wrapper();

        String roleCode = queryDTO.getRoleCode();
        wrapper.like(StringUtil.isNotEmpty(roleCode), SecRole::getRoleCode, roleCode);
        String roleName = queryDTO.getRoleName();
        wrapper.likeWithI18n(StringUtil.isNotEmpty(roleName), SecRole::getRoleName, roleName);
        String remark = queryDTO.getRemark();
        wrapper.likeWithI18n(StringUtil.isNotEmpty(remark), SecRole::getRemark, remark);
        wrapper.orderByAsc(SecRole::getRoleCode);

        Page<SecRole> pageResult = baseMapper.selectPageWithI18n(page, wrapper);
        List<SecRole> recordList = pageResult.getRecords();
        List<WebRoleDTO> returnList = RoleConvertUtil.secRole2WebRoleDTO(recordList);

        return returnList;
    }

    /**
     * 根据角色代码统计
     *
     * @param roleCode
     * @param excludeIds
     * @return
     */
    public long countByRoleCode(String roleCode, @Nullable Collection<Long> excludeIds) {
        LambdaQueryWrapper<SecRole> wrapper = Wrappers.lambdaQuery();

        wrapper.eq(SecRole::getRoleCode, roleCode);
        wrapper.notIn(CollectionUtil.isNotEmpty(excludeIds), SecRole::getId, excludeIds);

        return baseMapper.selectCount(wrapper);
    }

}
